/**
 * 节点布局交叉状态
 */
import { ComponentInternalInstance } from 'vue'

export default function useObserver(component: ComponentInternalInstance) {

  // Observer实例对象
  let observerInstance: UniApp.IntersectionObserver | null

  // 开始监听布局状态
  const connectObserver = (
    selector: string,
    top: number,
    fn: (res: UniApp.ObserveResult) => void
  ) => {
    // 开始监听前先停止开启的监听事件
    disconnectObserver()
    observerInstance = uni.createIntersectionObserver(component, {
      thresholds: [0.95, 0.98, 1]
    })
    // observerInstance.relativeTo('')
    observerInstance.relativeToViewport({
      top
    })
    observerInstance.observe(selector, (res: UniApp.ObserveResult) => {
      fn && fn(res)
    })
  }

  // 停止监听布局状态
  const disconnectObserver = () => {
    if (observerInstance) {
      observerInstance.disconnect()
      observerInstance = null
    }
  }

  return {
    connectObserver,
    disconnectObserver
  }
}